<template>
    <el-row>
        <el-col :span="24">
            <div class="grid-content ep-bg-purple-dark" />
            <el-card>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item>
                        <el-button type="success" @click="showAddDialog">添加</el-button>
                    </el-form-item>
                    <el-form-item style="float: right;">
                        <el-input v-model="rname" placeholder="请输入要搜索的姓名" @input="selectByPage(1)" />
                    </el-form-item>

                </el-form>
                <el-table :data="pageInfo.list" border style="width: 100%">
                    <el-table-column prop="rid" label="ID" width="50px" />
                    <!-- <el-table-column prop="eno" label="工号" /> -->
                    <el-table-column prop="eavatar" label="头像">
                        <template #default="scope">
                            <el-avatar shape="square" :size="50"
                                :src="'http://localhost:8080/upload/' + scope.row.eavatar" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="rname" label="姓名" />
                    <el-table-column prop="admin.username" label="账号名称" />
                    <el-table-column prop="rphone" label="联系电话" />
                    <el-table-column prop="estate" label="在职状态">
                        <template #default="scope">
                            <el-tag v-if="scope.row.estate == 1">在职</el-tag>
                            <el-tag type="info" v-else>离职</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="department.dname" label="部门名称" />
                    <el-table-column label="操作" width="300px">
                        <template #default="scope">
                             <el-button :disabled="scope.row.estate!= 1 || scope.row.admin.username" type="success" size="small"
                                @click="showAddAccountPwdDialog(scope.row.rid)">添加账密</el-button>
                            <el-button :disabled="scope.row.estate != 1" type="success" size="small"
                                @click="showUpdatAccountPwdDialog(scope.row.rid)">修改密码</el-button>
                            <el-button size="small" type="primary" @click="selectByRid(scope.row.rid)">修改</el-button>
                            <el-popconfirm title="你确定要离职该员工嘛" confirm-button-text="确认" cancel-button-text="取消"
                                @confirm="deleteByRid(scope.row.rid)">
                                <template #reference>
                                    <el-button size="small" type="danger">离职</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row class="row-bg" justify="center" style="margin-top: 20px;">
                    <el-pagination background layout="prev, pager, next" :total="pageInfo.total"
                        :page-size="pageInfo.pageSize" @change="selectByPage" />
                </el-row>

            </el-card>
        </el-col>
    </el-row>

    <!--添加员工的对话框开始-->
    <el-dialog v-model="addDialogshow" title=" 添加员工" width="500">
        <el-form>
            <el-form-item label="姓名" label-width="20%">
                <el-input v-model="employeeAdd.rname" autocomplete="off" style="width: 300px" />
            </el-form-item>
            <el-form-item label="联系电话" label-width="20%">
                <el-input v-model="employeeAdd.rphone" autocomplete="off" style="width: 300px" />
            </el-form-item>
            <el-form-item label="在职状态" label-width="20%">
                <el-radio-group v-model="employeeAdd.estate">
                    <el-radio value="1" size="large">在职</el-radio>
                    <el-radio value="2" size="large">离职</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="部门名称" label-width="20%">
                <el-select v-model="employeeAdd.did" placeholder="请选择部门" style="width: 300px">
                    <el-option v-for="(department, index) in departmentList" :key="index" :label="department.dname"
                        :value="department.did" />
                </el-select>
            </el-form-item>
            <el-form-item label="头像" label-width="20%">
                <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic"
                    :headers="headers" :show-file-list="false" :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addDialogshow = false">取消</el-button>
                <el-button type="primary" @click="insert">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!--添加员工的对话框结束-->
    <!--修改员工的对话框开始-->
    <el-dialog v-model="updateDialogShow" title=" 修改员工" width="500">
        <el-form>
            <el-form-item label="姓名" label-width="20%">
                <el-input v-model="employeeUpdate.rname" autocomplete="off" style="width: 300px" />
            </el-form-item>
            <el-form-item label="联系电话" label-width="20%">
                <el-input v-model="employeeUpdate.rphone" autocomplete="off" style="width: 300px" />
            </el-form-item>
            <el-form-item label="在职状态" label-width="20%">
                <el-radio-group v-model="employeeUpdate.estate">
                    <el-radio :value="1" size="large">在职</el-radio>
                    <el-radio :value="2" size="large">离职</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="部门名称" label-width="20%">
                <el-select v-model="employeeUpdate.did" placeholder="请选择部门" style="width: 300px">
                    <el-option v-for="(department, index) in departmentList" :key="index" :label="department.dname"
                        :value="department.did" />
                </el-select>
            </el-form-item>
            <el-form-item label="头像" label-width="20%">
                <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload" name="pic"
                    :headers="headers" :show-file-list="false" :before-upload="updateBeforeAvatarUpload"
                    :on-success="updateHandleAvatarSuccess">
                    <img v-if="imageUrlUpadte" :src="imageUrlUpadte" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateDialogShow = false">取消</el-button>
                <el-button type="primary" @click="update">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!--修改员工的对话框结束-->
    <!-- 添加账密的对话框开始 -->
    <el-dialog v-model="addAccountPwdDialogShow" title="添加账密" width="600px">
        <el-form>
            <el-form-item label="账号" label-width="20%">
                <el-input v-model="accountPwdData.username" autocomplete="off" style="width: 300px" />
            </el-form-item>
            <el-form-item label="密码" label-width="20%">
                <el-input v-model="accountPwdData.password" type="password" autocomplete="off" style="width: 300px" />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addAccountPwdDialogShow = false">取消</el-button>
                <el-button type="primary" @click="addAccountPwd">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 添加账密的对话框结束 -->
    <!-- 修改账密的对话框开始 -->
    <el-dialog v-model="updateAccountPwdDialogShow" title="修改密码" width="600px">
        <el-form>
            <!-- <el-form-item label="账号" label-width="20%">
                <el-input v-model="updatePwdData.username" autocomplete="off" style="width: 300px" />
            </el-form-item> -->
            <el-form-item label="密码" label-width="20%">
                <el-input v-model="updatePwdData.password" type="password" autocomplete="off" style="width: 300px" />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateAccountPwdDialogShow = false">取消</el-button>
                <el-button type="primary" @click="updateAccountPwd">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改账密的对话框结束 -->
</template>
<script setup>
import repairerApi from '@/api/repairerApi';
import { computed, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { ElLoading } from 'element-plus';
import departmentApi from '@/api/departmentApi';
import adminApi from '@/api/adminApi';
import { useTokenStore } from '@/stores/token';
// 新增：控制添加账密对话框是否显示
const addAccountPwdDialogShow = ref(false);
const updateAccountPwdDialogShow = ref(false);
const tokenStore = useTokenStore();
// 新增：存储添加账密对话框中的数据
const accountPwdData = ref({
    username: '',
    password: '',
    rid: ''
});
// 新增：存储修改账密对话框中的数据
const updatePwdData = ref({
    username: '',
    password: '',
    rid: ''
});

//定义方法完成员工添加
function insert() {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中~~~',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    repairerApi.insert(employeeAdd.value)
        .then(resp => {
            loading.close();
            if (resp.code == 10000) {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                //隐藏对话框
                addDialogshow.value = false;
                //清空对话框的数据
                employeeAdd.value = {
                    rid: '',
                    // eno: '',
                    rname: '',
                    rphone: '',
                    estate: '',
                    eavatar: '',
                    did: ''
                }
                //imgUrl清空
                imageUrl.value = "";
                selectByPage(pageInfo.value.pageNum);
            } else {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'error',
                    duration: 2000
                });
            }
        });
}
// 新增：添加账密的方法
function addAccountPwd() {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中~~~',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    repairerApi.insertAdmin(accountPwdData.value)
        .then(resp => {
            loading.close();
            if (resp.code == 10000) {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                //隐藏对话框
                addAccountPwdDialogShow.value = false;
                //清空对话框的数据
                accountPwdData.value = {
                    id: '',
                    username: '',
                    password: ''
                }
                selectByPage(pageInfo.value.pageNum);
            } else {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'error',
                    duration: 2000
                });
            }
        });
}
// 新增：修改账密的方法
function updateAccountPwd() {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中~~~',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    repairerApi.updateAdmin(updatePwdData.value)
        .then(resp => {
            loading.close();
            if (resp.code == 10000) {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                //隐藏对话框
                updateAccountPwdDialogShow.value = false;
                //清空对话框的数据
                updatePwdData.value = {
                    id: '',
                    username: '',
                    password: ''
                }
                selectByPage(pageInfo.value.pageNum);
            } else {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'error',
                    duration: 2000
                });
            }
        });
}
// 新增：显示添加账密对话框的方法
function showAddAccountPwdDialog(rid) {
    accountPwdData.value.rid = rid
    addAccountPwdDialogShow.value = true;
}
// 新增：显示修改账密对话框的方法
function showUpdatAccountPwdDialog(rid) {
    updatePwdData.value.rid = rid
    updateAccountPwdDialogShow.value = true;
}






//解决token跟头像上传冲突，设置请求头
const headers = computed(() => {
    let token = tokenStore.tokenStr;
    return { token };
})
//用来搜索姓名信息的 
const rname = ref('')
//分页信息
const pageInfo = ref({
    total: 0,
    pageSize: 0
});
//修改头像
const imageUrlUpadte = ref("");
//成功修改之前的回调
function updateBeforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片仅支持jpg格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能超过2m')
        return false
    }
    return true
}
//成功之后修改的回调
function updateHandleAvatarSuccess(resp, uploadFile) {
    console.log(resp);
    if (resp.code == 10000) {
        imageUrlUpadte.value = "http://localhost:8080/upload/" + resp.data;
        employeeUpdate.value.eavatar = resp.data;
    }
}
//修改对话框是否显示状态
const updateDialogShow = ref(false);
//被修改员工的信息
const employeeUpdate = ref({
    rid: '',
    // eno: '',
    rname: '',
    rphone: '',
    estate: '',
    eavatar: '',
    did: ''
});
//定义方法根据id查询员工的信息
function selectByRid(rid) {
    repairerApi.selectByRid(rid)
        .then(resp => {
            employeeUpdate.value = resp.data;
            departmentApi.selectAll()
                .then(resp => {
                    departmentList.value = resp.data;
                    imageUrlUpadte.value = `http://localhost:8080/upload/${employeeUpdate.value.eavatar}`;
                })
            //显示修改对话框
            updateDialogShow.value = true;
        })
}
//定义方法实现部门修改
function update() {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中~~~',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    repairerApi.update(employeeUpdate.value)
        .then(resp => {
            loading.close();
            if (resp.code == 10000) {
                //弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                updateDialogShow.value = false;
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage({
                    message: resp.msg,
                    type: 'error',
                    duration: 2000
                });
            }
        });
}

// 定义方法根据员工 rid 删除员工
function deleteByRid(rid) {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中~~~',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    repairerApi.delete(rid)
        .then(resp => {
            loading.close();
            if (resp.code == 10000) {
                // 弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                // 调用处理员工离职的接口
                repairerApi.handleEmployeeResignation(rid)
                //调用处理员工账号的接口
                adminApi.deleteByRid(rid)
                // 刷新表格
                selectByPage(pageInfo.value.pageNum)
                    .then(res => {
                        if (res.code != 10000) {
                            ElMessage({
                                message: res.msg,
                                type: 'error',
                                duration: 2000
                            });
                        }
                    });
            } else {
                // 弹出消息
                ElMessage({
                    message: resp.msg,
                    type: 'error',
                    duration: 2000
                });
            }
        });
}

//被添加的员工的信息
const employeeAdd = ref({
    rid: '',
    // eno: '',
    rname: '',
    rphone: '',
    estate: '',
    eavatar: '',
    did: ''

});

const imageUrl = ref("");
//添加对话框是否显示
const addDialogshow = ref(false);
//所有部门
const departmentList = ref([])
//上传图片之前的回调
function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片仅支持jpg格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能超过2m')
        return false
    }
    return true
}
//成功之后上传的回调
function handleAvatarSuccess(resp, uploadFile) {
    console.log(resp);
    if (resp.code == 10000) {
        imageUrl.value = "http://localhost:8080/upload/" + resp.data;
        employeeAdd.value.eavatar = resp.data;
    }
}
//分页查询
function selectByPage(pageNum) {
    repairerApi.selectByPage(pageNum, rname.value)
        .then(resp => {
            pageInfo.value = resp.data;

        })
}

//查询所有部门并显示添加对话框
function showAddDialog() {
    departmentApi.selectAll()
        .then(resp => {
            departmentList.value = resp.data;
            addDialogshow.value = true;
        })
}

selectByPage(1);
</script>
<style scoped>
.avatar-uploader,
.avatar {
    width: 178px;
    height: 178px;
    display: block;
    border: 1px dotted #dcdfe6;
    border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>